package com.mtsmda.jpa.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import com.mtsmda.jpa.dao.AuthorDAOI;
import com.mtsmda.jpa.domain.Author;

public class AuthorDAO implements AuthorDAOI {

	public EntityManager entityManager = Persistence
			.createEntityManagerFactory("MTSMDA").createEntityManager();

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public boolean addAuthor(Author author) {
		try {
			entityManager.getTransaction().begin();
			Author merge = entityManager.merge(author);
			if (merge == null) {
				throw new SQLException("Not add to database!");
			}
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean updateAuthor(Author author) {
		return addAuthor(author);
	}

	@Override
	public boolean deleteAuthor(Author author) {
		try {
			entityManager.getTransaction().begin();
			entityManager.remove(author);
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean deleteAllAuthors() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean truncateAuthors() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Author getAuthorById(Integer idAuthor) {
		try {
			Author findAuthor = entityManager.find(Author.class, idAuthor);
			if (findAuthor == null) {
				throw new SQLException("Not found in database!");
			}
			return findAuthor;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<Author> getAllAuthors() {
		try {
			TypedQuery<Author> createNamedQuery = entityManager
					.createNamedQuery("Author.getAll", Author.class);

			return createNamedQuery.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

}